package sa4.forms

import scala.collection.mutable.HashMap
import scala.xml._
import java.net._
import javax.servlet.http._
import javax.servlet.ServletConfig
import sa4.routing._

/*
 * An HTML form. Construct by passing a list of fields, the method and action parameters as strings,
 * and an optional map of parameters such as name, id and value.
 */
class Form(val fields: List[Field], val method: String, val action: URL, val attributes: HashMap[String, String], 
		   val f: (HashMap[String,String], HttpServletRequest, HttpServletResponse) => Unit) {
    
  def this(fields: List[Field], method: String, action: URL, attributes: HashMap[String, String]) = this(fields, method, action, attributes, null)
  def this(fields: List[Field], method: String, action: URL) = this(fields, method, action, new HashMap(), null)
    
  if(f != null) { method.toUpperCase() match {
    case "GET" => GET(action.toString, f); //println(GET.GETmap)
	//case "POST" => POST(action.toString, f)	  
  }}
  
  def buildHTML = {
    var attr = ""
    attributes.map(x => attr += " " + x._1 + "=\"" + x._2 + "\"") 
    var html = "<form " + "action=\"" + action + "\" method=\"" + method.toUpperCase() + "\""  +  attr  + ">"
    fields.map(x => html += x.buildHTML)
    html += "</form>"
    XML.loadString(html)
  }
}

/*
 * The field for an HTML form. Construct by passing the type of field as string, and an optional
 * map of parameters such as name, id and value.
 */
class Field(val `type`: String, val attributes: HashMap[String, String]) {
  def this(`type`: String) = this(`type`, HashMap())
  
  def setAttributes(newAttributes: Map[String, String]) {
    newAttributes.map(x => attributes(x._1) = (x._2))
  }
  
  def setAttribute(attr: (String, String)) {
    attributes(attr._1) = (attr._2)
  }
  
  def buildHTML = {
    var a = "";
    for(attr <- attributes.map(x => " " + x._1 + "=\"" + x._2 + "\"")) {
      a += attr
    }
    XML.loadString("<" + `type` + a + "/>")
    
  }
}